import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../model/channel.dart';
import '../sdk_service.dart';

class ChannelService extends GetConnect {
  final path = "cloud-digital-healing/channel/getChannelInfo";

  final storageKey = "com.hc.cure.hd.ChannelService";

  final _box = GetStorage();

  Future refresh() async {
    final sdk = Get.find<SDKService>();
    final hostURL = sdk.host;
    final absoluteURL = "$hostURL/$path";

    final PackageInfo info = await PackageInfo.fromPlatform();

    Map<String, dynamic> param = {};
    param["channelCode"] = sdk.channelCode;
    param["appId"] = info.packageName;

    final resp = await get(absoluteURL, query: param);

    final json = resp.body;
    final code = json["code"];
    if (code != 1) {
      return Future.error(json["msg"]);
    }
    final channelJSON = json["data"];
    await _box.write(storageKey, channelJSON);
  }

  String get channelID => channel?.channelId ?? "";

  Channel? get channel {
    final json = _box.read<Map<String, dynamic>>(storageKey);
    if (null == json) return null;
    return Channel.fromJson(json);
  }
}

final phaseStorageKey = "com.hc.cure.hd.ChannelService.phase";

extension ChannelServiceExtension on ChannelService {
  String get welcomePhase =>
      _box.read(phaseStorageKey) ??
      "您好～我是您的健康管家小惠！我能快速改善疼痛、咳嗽、压力大等多种症状，您可以问我健康问题，我会为您提供专业建议。";

  Future saveWelcomePhase(String phase) async {
    await _box.write(phaseStorageKey, phase);
    await _box.save();
  }
}
